//
//  CommunityViewController.m
//  FlowerRainGround
//
//  Created by lanou on 16/4/19.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "CommunityViewController.h"
#import "HeaderView.h"
#import "CycleScrollView.h"
#import "MyCollectionReusableView.h"

#import "CircleModel.h"
#import "TopicModel.h"
#import "RecommendModel.h"
#import "CustomerModel.h"
#import "FactoryCollectionViewCell.h"
#import "BaseCollectionViewCell.h"
#import "LORefresh.h"
#import "DetailPostViewController.h"

@interface CommunityViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>

@property (nonatomic, strong)UICollectionView *collectionView;//集合视图
@property (nonatomic, strong)UIScrollView *scrollView;//滚动视图

@property (nonatomic) NSInteger pageindex;
@property (nonatomic, strong) NSMutableArray *circleArray;//轮播数据源
@property (nonatomic, strong) NSMutableArray *hotTopicArray;//热门话题数据源
@property (nonatomic, strong) NSMutableArray *recommendArray;//推荐动态数据源
@property (nonatomic, strong)CycleScrollView *cycleScrollView;//轮播视图
@property (nonatomic, strong)UIScrollView *hotTopicScrollView;//热门话题滚动视图
@property (nonatomic)NSInteger pageSize;
@property (nonatomic)NSInteger currentPageIndex;

@end

@implementation CommunityViewController


#pragma mark --- 懒加载 ---

- (NSMutableArray *)circleArray {
    if (!_circleArray) {
        self.circleArray = [NSMutableArray array];
    }
    return _circleArray;
}

- (NSMutableArray *)hotTopicArray {
    if (!_hotTopicArray) {
        self.hotTopicArray = [NSMutableArray array];
    }
    return _hotTopicArray;
}

- (NSMutableArray *)recommendArray {
    if (!_recommendArray) {
        self.recommendArray = [NSMutableArray array];
    }
    return _recommendArray;
}

//轮播数据加载
- (void)handleCircleData {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://m.htxq.net/servlet/SysAdvertisingServlet?action=getAdList" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *totalDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
//                NSLog(@"totalDic:%@",totalDic);
        
        for (NSDictionary *modelDic in totalDic[@"result"]) {
            CircleModel *circleModel = [[CircleModel alloc] init];
            [circleModel setValuesForKeysWithDictionary:modelDic];
            [self.circleArray addObject:circleModel];
        }
        
        //        NSLog(@"circleArray:%@", self.circleArray);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
        
    }];
}

//热门话题数据加载
- (void)handleHotData {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://m.htxq.net/servlet/SysTagsServlet?action=getTagsList&currentPageIndex=0&pageSize=10" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *hotTopicDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
//                NSLog(@"hotTopicDic:%@", hotTopicDic);
        
        for (NSDictionary *modelDic in hotTopicDic[@"result"]) {
            
            TopicModel *topicModel = [[TopicModel alloc] init];
            [topicModel setValuesForKeysWithDictionary:modelDic];
            [self.hotTopicArray addObject:topicModel];
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            [self.collectionView.defaultFooter endRefreshing];
            [self.collectionView.defaultHeader endRefreshing];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error:%@",error);
        
    }];
    
}


//推荐动态数据加载
- (void)handleRecommendData {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//        manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [self.recommendArray removeAllObjects];
    [manager GET:@"http://app.htxq.net/servlet/UserBbsServlet?type=%E8%8D%90&action=getJianOrJingList&currentPageIndex=0" parameters:@{@"pageSize":@(self.pageSize)} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *recommendDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
//        NSLog(@"recommendDic:%@", recommendDic);
        
        for (NSDictionary *modelDic in recommendDic[@"result"]) {
            
            RecommendModel *recommendModel = [[RecommendModel alloc] init];
            [recommendModel setValuesForKeysWithDictionary:modelDic];
            [self.recommendArray addObject:recommendModel];
            
            CustomerModel *customerModel = [[CustomerModel alloc] init];
            [customerModel setValuesForKeysWithDictionary:modelDic[@"customer"]];
            recommendModel.customerModel = customerModel;
        }
        //        NSLog(@"recommendArray:%@",self.recommendArray);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.collectionView reloadData];
            
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error:%@", error);

    }];
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageSize = 10;
    self.navigationItem.title = @"社区";
    [self handleHotData];
    [self createNavigationBar];
    [self handleCircleData];
    [self handleRecommendData];
    
    [self createCollectionView];
    [self refresh];
}

#pragma mark --- 上拉刷新 ---
- (void)refresh {
    
    __block typeof(self) myself = self;
    //下拉刷新
    [self.collectionView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        _pageSize = 0;
        [myself.collectionView.defaultHeader endRefreshing];
        [myself handleRecommendData];
    }];
    
    //上拉加载
    [self.collectionView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        _pageSize += 20;
        [myself.collectionView.defaultHeader endRefreshing];
        [myself handleRecommendData];
    }];
}


#pragma mark --- 视图创建 ---
//创建导航栏
- (void)createNavigationBar {
    NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"HeaderView" owner:nil options:nil];
    HeaderView *headerView = [views lastObject];
    headerView.frame = self.navigationController.navigationBar.frame;
    self.navigationItem.titleView = headerView;
    self.navigationController.navigationBar.translucent = NO;
}

//创建集合视图
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(kWidth/2 - 4, kWidth/2);
    layout.minimumLineSpacing = 2;
    layout.minimumInteritemSpacing = 2;
    
    //设置集合视图的滑动方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(2, 2, 2, 2);
    layout.headerReferenceSize = CGSizeMake(kWidth, kHeight * 2 / 3);
    
    _collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    
    [_collectionView registerNib:[UINib nibWithNibName:@"RecommendCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([RecommendModel class])];
    
    
    [_collectionView registerClass:[MyCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.view addSubview:_collectionView];
}

//创建滚动视图
- (void)createScrollView {
    _cycleScrollView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight / 3) animationDuration:2.0];
    NSMutableArray *viewsArray = [NSMutableArray array];
    for (int i = 0; i < self.circleArray.count; i ++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:_cycleScrollView.bounds];
        
        CircleModel *circleModel = self.circleArray[i];
//        NSLog(@"%@",self.circleArray);
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:circleModel.imageUrl]];
        [viewsArray addObject:imageView];
    }
    _cycleScrollView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex) {
        return viewsArray[pageIndex];
    };
    _cycleScrollView.totalPagesCount = viewsArray.count;
    
    _cycleScrollView.TapActionBlock = ^(NSInteger pageIndex) {
        
    };
}


#pragma mark --- collectionView代理方法 ---
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.recommendArray.count;
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        
    BaseModel *recommendModel = self.recommendArray[indexPath.row];
    
    BaseCollectionViewCell *cell = [FactoryCollectionViewCell createCollectionViewCellWithModel:recommendModel collection:collectionView indexPath:indexPath];
    [cell setDataWithModel:recommendModel];
        return cell;
        
    
}


//头尾视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
        MyCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        [self createScrollView];
        [view addSubview:self.cycleScrollView];
    
    UILabel *topiclabel =[[UILabel alloc] initWithFrame:CGRectMake(0 , kHeight / 3, kWidth, 30)];
    topiclabel.text = @"热门话题";
    [view addSubview:topiclabel];
    
    
    
    CGFloat imageHeight = kHeight/3 - 60;
    self.hotTopicScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kHeight / 3 + 30, kWidth, kHeight / 3 - 60)];
    self.hotTopicScrollView.backgroundColor = [UIColor clearColor];
    self.hotTopicScrollView.contentSize = CGSizeMake(imageHeight * 5, imageHeight);
    self.hotTopicScrollView.bounces = NO;
    self.hotTopicScrollView.pagingEnabled = NO;
    self.hotTopicScrollView.showsHorizontalScrollIndicator = NO;
//    NSLog(@"---------%@",self.hotTopicArray);
  
    if (self.hotTopicArray.count > 0) {
        
    
    for (int i = 0; i < 5; i ++) {
        UIImageView *imageVeiw = [[UIImageView alloc] initWithFrame:CGRectMake(i * imageHeight, 0, imageHeight, imageHeight)];

        TopicModel *model = self.hotTopicArray[i];
        [imageVeiw sd_setImageWithURL:[NSURL URLWithString:model.ico]];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageHeight - 20, imageHeight, 20)];
        label.text = [NSString stringWithFormat:@"#%@#",model.name];
        label.alpha = 0.4;
        label.textAlignment = 1;
        label.backgroundColor = [UIColor orangeColor];
        [imageVeiw addSubview:label];
        
        [self.hotTopicScrollView addSubview:imageVeiw];
    }
    }
    [view addSubview:self.hotTopicScrollView];
    
    
    UILabel *recommendLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, kHeight *2/3 - 30, kWidth, 30)];
    recommendLabel.text = @"推荐动态";
    [view addSubview:recommendLabel];
    
        return view;
 
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    DetailPostViewController *detailVC = [[DetailPostViewController alloc] init];
    detailVC.recommendArray = self.recommendArray;
    detailVC.index = indexPath.row;
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
